<template>
  <el-container class="container">
    <el-header>Header</el-header>
    <el-container>
      <el-aside class="aside" width="200px">
        <el-menu
          v-for="item in state.menuList"
          :key="item['id']"
          :default-active="state.activeMenu"
          @select="menuSelect"
          router
        >
          <el-sub-menu v-if="item['children']['length']" :index="item['path']">
            <template #title>{{ item['name'] }}</template>
            <el-menu-item
              v-for="child in item['children']"
              :key="child['id']"
              :index="child['path']">
              {{ child['name'] }}
            </el-menu-item>
          </el-sub-menu>
          <el-menu-item v-else :index="item['path']">
            {{ item['name'] }}
          </el-menu-item>
        </el-menu>
      </el-aside>
      <el-main style="background-color: #eee">
        <router-view></router-view>
      </el-main>
    </el-container>
  </el-container>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive } from 'vue'
import { Message, Menu, Setting } from '@element-plus/icons-vue'
import { getMenusList } from '@/api/permit'
import { useRouter } from 'vue-router'
import { setLocal } from '@/utils/local'

export default defineComponent({
  name: 'home',
  components: {
    Message,
    Setting,
    'icon-menu': Menu
  },
  // 相当于原 beforeCreate、created生命周期钩子函数
  setup() {
    // 获取router实例
    const router = useRouter()
    // reactive定义多个数据的响应式
    const state = reactive({
      menuList: [
        {
          children: [],
          id: 0,
          name: "首页",
          path: "welcome"
        }
      ],
      activeMenu: 'welcome'
    })
    // 获取菜单列表
    const getMenus = () => {
      getMenusList().then(res => {
        if (res.data.code === 200) {
          const data = res.data
          setLocal('menus', JSON.stringify(data.data))
          state.menuList = state.menuList.concat(data.data)
          goToPath()
        }
      })
    }
    // 选中菜单事件
    const menuSelect = (index: string) => {
      state.activeMenu = index
    }
    // 跳转菜单路由，刷新跳到当前路由
    const goToPath = () => {
      const path = router.currentRoute.value.path.split('/')[1]
      if (path === 'home') {
        router.push('/welcome')
        state.activeMenu = 'welcome'
        return
      }
      router.push('/' + path)
      state.activeMenu = path
    }
    // 相当于原 mounted生命周期钩子函数
    onMounted(() => {
      getMenus()
    })

    return {
      state,
      menuSelect
    }
  }
})
</script>

<style lang="less" scoped>
.container {
  height: 100vh;
}
.el-header {
  background-color: #b3c0d1;
  color: var(--el-text-color-primary);
  text-align: center;
  line-height: 60px;
}
</style>
